package com.shop.shopmall.utils;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

import static org.apache.tomcat.util.http.fileupload.FileUtils.deleteDirectory;

public class FileUtils {

    /**
     * 解压zip文件
     *
     * @param file
     * @throws IOException
     */
    public static void unzip(MultipartFile file, String uploadZipPath) throws IOException {
        String fileName = file.getOriginalFilename();
        String filePath = uploadZipPath + File.separator + fileName;
        File zipFile = new File(filePath);
        file.transferTo(zipFile);
        String outputBaseName = fileName.substring(0, fileName.lastIndexOf("."));
        // 检查解压目标是否存在，如果存在则删除以准备覆盖
        File potentialOutputDir = new File(uploadZipPath, outputBaseName);
        if (potentialOutputDir.exists()) {
            // 递归删除目录及其内容，注意这将永久删除原有文件，请谨慎使用
            deleteDirectory(potentialOutputDir);
            System.out.println("已删除存在的文件/目录准备覆盖解压: ");
        }
        ZipFile zip = new ZipFile(zipFile);
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            File destPath = new File(uploadZipPath, entry.getName());
            if (entry.isDirectory()) {
                destPath.mkdirs();
            } else {
                destPath.getParentFile().mkdirs();
                try (InputStream in = zip.getInputStream(entry);
                     FileOutputStream out = new FileOutputStream(destPath)) {
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                }
            }
        }
        zip.close();
        zipFile.delete();
    }

}
